import React, { PureComponent } from 'react';

import videojs from 'video.js';
// 引入视频框架的专属样式
import "video.js/dist/video-js.css";
import { Button, message } from 'antd';
import Axios from 'axios';
import { webSite } from '../../website';
export default class TVPlay extends PureComponent {
  constructor(props) {
    super(props);
    this.player = null;
    this.state = {
      // 猜你喜欢列表
      FilmAll: [],
      // 电影的url
      url: '',
      // 切换播放源
      info: [],
      // 显示所有的集数
      TvList: [],
      // 当前集数
      index: 0,
      // 源1
      TvlistOne: {},
      // 源2
      TvlistTwo: {},
      // 在哪个源
      isType: 1
    }
  }

  componentWillUnmount () {
    // 销毁播放器
    if (this.player) {
      this.player.dispose();
    }
    // 卸载异步操作设置状态
    this.setState = (state, callback) => {
      return;
    }
  }

  componentDidMount () {
    let { transformation, index, url } = this.props.location.state;
    this.setState({
      index
    }, () => {
      // 加载猜你喜欢
      this.getFilm();
      // 加载视频
      if (transformation) {
        Axios.create({
          baseURL: `${webSite}:3003`
        }).post("/getUrlOne", { url }).then(err => {
          if (err.data.code === "G0001") {
            this.getUrlHrefAll(err.data.CarouselUrl)
          }
        }).catch(() => {
          message.error({ content: '网络错误', className: 'bulletChatMessage' });
        })
      } else {
        this.getUrlHrefAll(url)
      }
    })
  }

  // 根据url获取所有的数据
  getUrlHrefAll = (url) => {
    const _this = this;
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/getUrlHrefAll", { url }).then(err => {
      if (err.data.code === "P0001") {
        if (err.data.info[0]) {
          this.setState({
            // 源1
            TvlistOne: err.data.info[0],
          })
        }
        if (err.data.info[1]) {
          this.setState({
            // 源2
            TvlistTwo: err.data.info[1],
          })
        }
        // 把请求回来的数据赋值
        this.setState({
          // 第一集的url
          url: err.data.url
        }, () => {
          _this.player = videojs("video");
          _this.player.controls(true)
          _this.player.src(_this.state.url)
          _this.player.play().catch(() => {
            message.info({ content: '电视剧需要缓冲，请勿操作过快', className: 'bulletChatMessage' })
          })
        })
      } else if (err.data.code === "P0002") {
        message.error({ content: '暂无该视频的资源', className: 'bulletChatMessage' });
      }
    }).catch(() => { })
  }

  // 猜你喜欢请求
  getFilm = () => {
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/getStart", { type: 'tv' }).then(err => {
      if (err.data.code === 'G0001') {
        let all = err.data.All;
        let FilmAll = [];
        for (let index = 0; index < 6; index++) {
          if (all.length > 0) {
            let n = Math.floor(Math.random() * all.length) //随机抽取的索引值
            FilmAll.push(all.splice(n, 1)[0]) //在把删除的值放入被删数组
          }
        }
        this.setState({
          FilmAll
        })
      }
    }).catch(() => {
      message.error({ content: '网络错误', className: 'bulletChatMessage' });
    })
  }

  // 跳转到搜索页面
  goSearch = () => {
    this.props.history.replace('/Movies/Search')
  }

  // 点击图标跳转到本地
  goMoviesHome = () => {
    this.props.history.replace('/Movies')
  }

  // 当前集数显示样式
  classIndex = (int, type) => {
    let { index, isType } = this.state;
    if (index === int && type === isType) {
      return 'filmPlayUlIndex borderColor';
    }
    return 'filmPlayUlIndex';
  }

  // 选择集数
  GoSelectedWorks = (list, index, type) => {
    this.setState({
      index,
      isType: type
    }, () => {
      // 把url链接分离出来
      let urlLang = list.substring(list.indexOf('$') + 1);
      let url = urlLang.substring(0, urlLang.indexOf('$'));
      this.player = videojs("video");
      this.player.controls(true)
      this.player.src(url)
      this.player.play().catch(() => {
        message.info({ content: '电视剧需要缓冲，请勿操作过快', className: 'bulletChatMessage' })
      })
    })
  }

  // 猜你喜欢的点击
  GoSelectedCai = (list) => {
    if (!list.CarouselUrl) {
      return;
    }
    this.props.history.push({ pathname: "/Movies/TVPlay", state: { url: list.CarouselUrl, title: list.CarouselText, index: 0, transformation: false } });
    // 刷新网页
    window.history.go(0);
  }

  render () {
    let { FilmAll, index, TvlistOne, TvlistTwo } = this.state;
    let { title } = this.props.location.state;
    return (
      <div className='filmPlay'>
        <div className='MoviesHeader'>
          {/* 顶部logo */}
          <div className='MoviesHeader_logo'>
            <img src={require('../image/tv.png')} alt="logo" onClick={this.goMoviesHome} />
          </div>
          <div className='MoviesHeader_search'>
            <Button className='MoviesHeaderViesInput' type='text' onClick={this.goSearch}>输入你想看的</Button>
          </div>
          <div className='MoviesHeader_bottom'>
            <Button type='text' className='MoviesHeader_bottom_body' onClick={this.goSearch}>全网搜索</Button>
          </div>
        </div>
        {/* 内容 */}
        <video id="video" className="video-js vjs-default-skin video" ></video>
        <h3 className='title' style={{ paddingLeft: '5vw' }}>{title}&nbsp;&nbsp;第{index + 1}集</h3>

        {/* 集数显示 */}
        {
          TvlistOne.flag_name !== undefined ?
            <div>
              <p className='title_is'>{TvlistOne.flag_name}</p>
              <div className='filmPlayUlList'>
                {
                  TvlistOne.video !== undefined ?
                    TvlistOne.video.map((list, index) => {
                      return (
                        <Button type='text' className={this.classIndex(index, 1)} key={index} onClick={() => this.GoSelectedWorks(list, index, 1)}>{index + 1}</Button>
                      )
                    })
                    : ''
                }
              </div>
            </div>
            : ''
        }

        {
          TvlistTwo.flag_name !== undefined ?
            <div>
              <p className='title_is'>{TvlistTwo.flag_name}</p>
              <div className='filmPlayUlList'>
                {
                  TvlistTwo.video !== undefined ?
                    TvlistTwo.video.map((list, index) => {
                      return (
                        <Button type='text' className={this.classIndex(index, 2)} key={index} onClick={() => this.GoSelectedWorks(list, index, 2)}>{index + 1}</Button>
                      )
                    })
                    : ''
                }
              </div>
            </div>
            : ''
        }

        {/* 猜你喜欢 */}
        <div className='filmPlay_love'>
          <div className='filmPlay_love_title'>猜你喜欢</div>
          <ul className='filmPlayUl'>
            {
              FilmAll.length !== 0 ?
                FilmAll.map((list, index) => {
                  return (
                    <li key={index} onClick={() => this.GoSelectedCai(list)}>
                      <img src={list.CarouselImg} alt={list.CarouselText} />
                      <p>{list.CarouselText}</p>
                    </li>
                  )
                })
                : ''
            }
          </ul>
        </div>
        <span className='moviesPlay_sapn'>电影内容来源自互联网、如有冒犯，立即删除</span>
      </div>
    )
  }
}